package com.example.black.myapplication.materia;

import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;

import com.example.black.myapplication.R;

public class TextInputLayoutActivity extends AppCompatActivity {

    private TextInputLayout textInputLayoutWithCounter;
    private TextInputLayout textInputLayoutWithCustomCounter;
    private TextInputEditText etWithCounter;
    private TextInputEditText etWithCustomCounter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_inputlayout);
        initView();
    }

    private void initView() {
        textInputLayoutWithCounter = findViewById(R.id.textInputLayoutWithCounter);
        textInputLayoutWithCustomCounter = findViewById(R.id.textInputLayoutWithCustomCounter);
        etWithCounter = findViewById(R.id.etWithCounter);
        etWithCounter.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > textInputLayoutWithCounter.getCounterMaxLength()){
                    textInputLayoutWithCounter.setError("Max character length is " + textInputLayoutWithCounter.getCounterMaxLength());
                } else{
                    textInputLayoutWithCounter.setError(null);
                }

            }
        });
        etWithCustomCounter = findViewById(R.id.etWithCustomCounter);
        etWithCustomCounter.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > textInputLayoutWithCustomCounter.getCounterMaxLength()){
                    textInputLayoutWithCustomCounter.setError("Max character length is " + textInputLayoutWithCustomCounter.getCounterMaxLength());
                } else{
                    textInputLayoutWithCustomCounter.setError(null);
                }
            }
        });
    }
}
